package com.jason.fingerprint.service;

import android.app.Service;
import android.content.*;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.beans.DailyReportBean;
import com.jason.fingerprint.beans.LeaveOutBean;
import com.jason.fingerprint.beans.SignInRecordBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.common.PreferenceHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.logic.SignInUploadLogic;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.utils.DataUtils;
import org.kymjs.aframe.database.KJDB;

/**
 * @ClassName: InitService
 * @Description: 初始化信息服务处理
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-9-5 13:16:41
 */
public class InitService extends Service {

    private static final String TAG = InitService.class.getSimpleName();

    public static final String ACTION_INIT = "action_init";

    private InitBroadcastReceiver mInitBroadcastReceiver;

    private AppContext mAppContext;

    private KJDB mKJDB;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        mAppContext = AppContext.getInstance();
        mKJDB = AppContext.mInstance.getKjdb();
        mInitBroadcastReceiver = new InitBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_INIT);
        this.registerReceiver(mInitBroadcastReceiver,intentFilter);
        //开始处理
        sendBroadcast(new Intent(ACTION_INIT));
    }

    private void deleteDataFromTable(){
        Log.i(TAG,"deleteDataFromTable begin...");
        PreferenceHelper.setDeleteTableToday(mAppContext, DataUtils.getToday());
        //删除日常签到信息
        try{
            mKJDB.deleteByWhere(DailyReportBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }
        //删除矫正人员签到信息
        try{
            mKJDB.deleteByWhere(SignInRecordBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }

        //删除矫正人员请假
        try{
            mKJDB.deleteByWhere(LeaveOutBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }

        //删除工作走访
        try{
            mKJDB.deleteByWhere(WorkVisitBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    public class InitBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG,"action:" + action);
            if (ACTION_INIT.equals(action)){
                // 判断是否是当前第一次进入程序。执行上传记录
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String day = PreferenceHelper.getFirstToday(mAppContext);
                        Log.i(TAG,"day:" + day);
                        Log.i(TAG,"getToday:" + DataUtils.getToday());
                        if (!DataUtils.getToday().equals(day)){
                            SignInUploadLogic logic = new SignInUploadLogic(mAppContext,mUploadHandler, "");
                            logic.execute();
                        }

                        // 删除1个月之前未上传记录
                        String date = PreferenceHelper.getDeleteTableToday(mAppContext);
                        if (TextUtils.isEmpty(date)){
                            deleteDataFromTable();
                        }else{
                            if (DataUtils.daysBetween(DataUtils.getToday(),date) >= 180){
                                deleteDataFromTable();
                            }
                        }
                    }
                }).start();

            }
        }
    }

    private Handler mUploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG,"what:" + msg.what);
            switch (msg.what) {
                case UIHelper.SIGNIN_UPLOAD_SUCCESS:
                    //TODO 上传资源
                    uploadImageOrAudio();
                    break;
                case UIHelper.SIGNIN_UPLOAD_ERROR:
                case UIHelper.SIGNIN_UPLOAD_FAIL:
                    // 上传签到失败 --不区别失败的种类
                    uploadImageOrAudio();
                    break;
                case UIHelper.FILE_UPLOAD_SUCCESS:
                    PreferenceHelper.setFirstToday(mAppContext,DataUtils.getToday());
                    break;
                case UIHelper.FILE_UPLOAD_FAIL:
                    PreferenceHelper.setFirstToday(mAppContext,DataUtils.getToday());
                    break;
                default:
                    break;
            }
        }

    };

    private void uploadImageOrAudio() {
        UploadToTempSyncLogic logic = new UploadToTempSyncLogic(
                mAppContext, mUploadHandler, true, "");
        logic.execute();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
        try {
            this.unregisterReceiver(mInitBroadcastReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //不让用户强制关闭服务
        startService(new Intent(this, InitService.class));
    }
}
